package com.junxonline.instant.admin.service.file.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.junxonline.instant.dao.entity.dto.file.UploadFileDTO;
import com.junxonline.instant.dao.entity.vo.file.UploadFileVO;
import com.junxonline.instant.admin.service.file.UploadFileService;
import com.junxonline.instant.common.util.admin.MinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文件上传接口实现类
 *
 * @author JunX
 * @date 2021-12-10
 */
@Service
@Transactional
public class UploadFileServiceImpl implements UploadFileService {

    @Autowired
    private MinioUtils minioUtils;

    /**
     * 获取临时上传地址
     *
     * @param vo 请求参数
     * @return UploadFileDTO
     */
    @Override
    public UploadFileDTO getSignedUploadFileUrl(UploadFileVO vo) {
        String bucketName = vo.getBucketName();
        String originName = vo.getOriginName();
        int lastPointIndex = originName.lastIndexOf(".");
        String suffix = originName.substring(lastPointIndex);
        String objectName = IdUtil.simpleUUID() + suffix;
        String path = DateUtil.format(DateUtil.date(), "yyyyMM") + "/" + objectName;
        // 生成临时加密链接
        String url = minioUtils.preSignedPutObject(bucketName, path);
        return new UploadFileDTO(objectName, url);
    }

    /**
     * 获取临时上传地址(原始文件名)
     *
     * @param vo 请求参数
     * @return UploadFileDTO
     */
    @Override
    public UploadFileDTO getSignedUploadFileUrlOriginName(UploadFileVO vo) {
        String bucketName = vo.getBucketName();
        String originName = vo.getOriginName();
        String path = DateUtil.format(DateUtil.date(), "yyyyMM") + "/" + vo.getOrganizationId() + "/" + originName;
        // 生成临时加密链接
        String url = minioUtils.preSignedPutObject(bucketName, path);
        return new UploadFileDTO(originName, url);
    }
}
